package com.cjw.service.impl.userMange;

import com.cjw.enums.user.UserType;
import com.cjw.mapper.database.RoleMapper;
import com.cjw.mapper.database.UserHasRoleMapper;
import com.cjw.mapper.database.UserMapper;
import com.cjw.mapper.systemManage.ExamineMapper;
import com.cjw.mapper.userMange.BlackListMapper;
import com.cjw.pojo.dto.database.PageDTO;
import com.cjw.pojo.dto.database.UserDTO;
import com.cjw.pojo.dto.userMange.UserAuthorSimpleDTO;
import com.cjw.pojo.dto.userMange.UserSimpleDTO;
import com.cjw.pojo.entity.database.Role;
import com.cjw.pojo.entity.database.User;
import com.cjw.pojo.entity.database.UserHasRole;
import com.cjw.pojo.entity.systemManage.Examine;
import com.cjw.pojo.entity.userMange.BlackList;
import com.cjw.pojo.query.systemManage.AddUserRole;
import com.cjw.pojo.query.systemManage.QueryAuthorDTO;
import com.cjw.pojo.query.userMange.UserQuery;
import com.cjw.service.userMange.UserAccountService;
import com.cjw.util.BaseContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author : cjw
 * @date: : 2022/2/7 14:34
 * @description : 用户管理 Service
 */
@Service("userAccountService")
public class UserAccountServiceImpl implements UserAccountService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ExamineMapper examineMapper;

    @Autowired
    private UserHasRoleMapper userHasRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private BlackListMapper blackListMapper;

    @Override
    public PageDTO<List<UserSimpleDTO>> findAllUsers(UserQuery userQuery) {
        ArrayList<UserSimpleDTO> userSimpleDTOS = new ArrayList<>();
        PageDTO<List<UserSimpleDTO>> listPageDTO = new PageDTO<>();
        userQuery.setPage((userQuery.getPage()-1)*userQuery.getSize());
        listPageDTO.setTotal(userMapper.findAllUsersByPageCount(userQuery));
        for (User user : userMapper.findAllUsersByPage(userQuery)) {
            UserSimpleDTO userSimpleDTO = new UserSimpleDTO();
            userSimpleDTO.setId(user.getId());
            userSimpleDTO.setAddTime(user.getAddTime());
            userSimpleDTO.setTelephone(user.getPhone());
            userSimpleDTO.setUserName(user.getUserName());
            userSimpleDTO.changeState(user.getState());
            UserHasRole userHasRole = new UserHasRole();
            userHasRole.setUserId(user.getId());
            UserHasRole userHasRole1 = userHasRoleMapper.selectOne(userHasRole);
            userSimpleDTO.setRole(roleMapper.selectByPrimaryKey(userHasRole1.getRoleId()).getName());
            userSimpleDTOS.add(userSimpleDTO);
        }
        listPageDTO.setDtos(userSimpleDTOS);
        return listPageDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer changeUserState(Long id) {
        User user = new User();
        user.setId(id);
        user.setState(userMapper.selectOne(user).getState() == 0 ? 1 : 0);
        userMapper.updateByPrimaryKeySelective(user);
        return user.getState();
    }

    @Override
    public PageDTO<List<UserAuthorSimpleDTO>> findAllUsersAuthor(QueryAuthorDTO queryAuthorDTO) {
        queryAuthorDTO.setPage((queryAuthorDTO.getPage()-1)*queryAuthorDTO.getSize());
        PageDTO<List<UserAuthorSimpleDTO>> listPageDTO = new PageDTO<>();
        List<UserAuthorSimpleDTO> dtos = new ArrayList<>();
        for (UserAuthorSimpleDTO userAuthorSimpleDTO : userMapper.findAllUserAuthorList(queryAuthorDTO)) {
            if (userAuthorSimpleDTO.getAddTime() == null)
                userAuthorSimpleDTO.setUnPassNumber(0);
            Examine examine = new Examine();
            examine.setUserId(userAuthorSimpleDTO.getUserId());
            examine.setType(userAuthorSimpleDTO.getType());
            double unPassPer = examineMapper.selectCount(examine) ==0.00 ? 0 :
                    new BigDecimal((float) userAuthorSimpleDTO.getUnPassNumber() / examineMapper.selectCount(examine)).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
            userAuthorSimpleDTO.setUnPassPer(unPassPer*100);
            BlackList blackList = new BlackList();
            blackList.setUserId(userAuthorSimpleDTO.getUserId());
            blackList.setType(userAuthorSimpleDTO.getType());
            userAuthorSimpleDTO.setState(blackListMapper.selectCount(blackList) == 0 ? "正常" : "禁言");
            dtos.add(userAuthorSimpleDTO);
        }
        listPageDTO.setDtos(dtos);
        listPageDTO.setTotal(userMapper.findAllUserAuthorCount(queryAuthorDTO));
        return listPageDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean ban(Long userId, Integer type) {
        BlackList blackList = new BlackList();
        blackList.setType(type);
        blackList.setUserId(userId);
        blackList.setAddTime(new Date());
        UserDTO user = (UserDTO) BaseContextHolder.get("user");
        blackList.setAdminId(user.getId());
        return blackListMapper.insertSelective(blackList) == 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean unseal(Long userId, Integer type) {
        BlackList blackList = new BlackList();
        blackList.setType(type);
        blackList.setUserId(userId);
        return blackListMapper.delete(blackList) == 1;
    }

    @Override
    public Boolean isInBlackList(Integer type) {
        BlackList blackList = new BlackList();
        UserDTO user = (UserDTO) BaseContextHolder.get("user");
        blackList.setUserId(user.getId());
        blackList.setType(type);
        return blackListMapper.selectOne(blackList) != null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addRole(AddUserRole addUserRole) {
        String name = roleMapper.selectByPrimaryKey(addUserRole.getRoleId()).getName();
        User user = new User();
        user.setId(addUserRole.getUserId());
        if (name.equals("用户")) {
            user.setType(UserType.ADMIN.getCode());
        } else {
            user.setType(UserType.USER.getCode());
        }
        userMapper.updateByPrimaryKeySelective(user);
        UserHasRole userHasRole = new UserHasRole();
        userHasRole.setRoleId(addUserRole.getRoleId());
        userHasRole.setUpdateTime(new Date());
        Example example = new Example(UserHasRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", addUserRole.getUserId());
        return userHasRoleMapper.updateByExampleSelective(userHasRole, example) == 1;
    }

}
